#include "entityeditor.h"
#include "ui_entityeditor.h"

EntityEditor::EntityEditor(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::EntityEditor)
{
    ui->setupUi(this);

    model=new QStringListModel(this);
    ui->listView->setModel(model);
}

EntityEditor::~EntityEditor()
{
    delete ui;
}

void EntityEditor::on_btn_load_clicked()
{
    fileName=QFileDialog::getOpenFileName(this,"选择配置文件",
                                          QString(),"配置文件 (*.json)");
    if(fileName.isEmpty())
        return;

    entity.setFileName(fileName);
    if(entity.load())
    {
        QStringList items=entity.keys();
        if(!items.isEmpty())
            model->setStringList(items);
    }
    else {
        QMessageBox::warning(this,"操作未完成",
                             "无法加载配置文件！");
    }
}

void EntityEditor::on_btn_create_clicked()
{
    fileName.clear();
    entity.clear();
    if(model->rowCount() != 0)
        model->setStringList(QStringList());
}

void EntityEditor::on_btn_add_clicked()
{
    AddItem item;
    connect(&item,&AddItem::addItem,this,&EntityEditor::addItem);
    item.exec();
}

void EntityEditor::addItem(const QString &key, const QString &value)
{
    entity.insert(key,value);
    model->setStringList(entity.keys());
}

void EntityEditor::on_btn_remove_clicked()
{
    auto index=ui->listView->currentIndex();
    if(index.isValid())
    {
        auto key=index.data().toString();
        entity.remove(key);
        model->setStringList(entity.keys());
    }
}

void EntityEditor::on_btn_save_clicked()
{
    if(entity.isEmpty())
        return;

    if(fileName.isEmpty())
    {
        fileName=QFileDialog::getSaveFileName(this,"设置保存文件",
                                              QString(),
                                              "配置文件 (*.json)");
        if(!fileName.isEmpty())
            entity.setFileName(fileName);
        else
            return;
    }

    if(entity.save())
        QMessageBox::information(this,"操作完成",
                                 "文件已保存到：" + fileName);
}

void EntityEditor::on_listView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        auto key=index.data().toString();
        auto value=entity.value(key).toString();
        if(!value.isEmpty())
            ui->value->setPlainText(value);
    }
}

void EntityEditor::on_btn_edit_clicked()
{
    auto index=ui->listView->currentIndex();
    if(index.isValid())
    {
        auto key=index.data().toString();
        auto value=entity.value(key).toString();
        AddItem item;
        item.setItem(key,value);
        connect(&item,&AddItem::addItem,this,&EntityEditor::addItem);
        item.exec();
    }
}
